package com.intexh.quickandroid.web.manager;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.intexh.quickandroid.BuildConfig;
import com.intexh.quickandroid.utils.LogCatUtil;
import com.intexh.quickandroid.web.ui.WebViewActivity;


public class WebViewClientUtil extends WebViewClient {
    private final WebClientLoadListener loadListener;
    Activity activity;

    private boolean isError;

    public WebViewClientUtil(Activity activity,WebClientLoadListener loadListener) {
        this.activity = activity;
        this.loadListener = loadListener;
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
//        if(url.contains("tel:")){
//            callPhone(url) ;
//            return true;
//        }

        LogCatUtil.e("frank","加载的网页："+url);
        if(url.startsWith(BuildConfig.SERVERHEAD)){ //非本站域名 不跳转新的页面
            WebViewActivity.startActivity(activity,url);
            return true;
        }
        return super.shouldOverrideUrlLoading(view, url);
    }

    private void callPhone(String url) {
//        String mobile = url.substring(url.lastIndexOf(":") + 1);
//        Uri uri = Uri.parse("tel:" + mobile);
//        Intent intent = new Intent(Intent.ACTION_DIAL, uri);
//        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        activity.startActivity(intent);
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        isError=false;
    }

    @Override
    public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
        super.onReceivedError(view, request, error);
        isError = true;
    }

    /**
     * 界面加载完后回调
     * @param view
     * @param url
     */
    @Override
    public void onPageFinished(WebView view, String url) {
        String title = view.getTitle(); // 获取网页标题
        loadListener.loadFinished(title,isError);
        super.onPageFinished(view, url);
    }
    public interface WebClientLoadListener{
        void loadFinished(String title, boolean isError);
    }

}